const { shareData } = require("../commands/share_data");
const { copy, get_fst_file, write_plain } = require("./file_tool");
const { warn } = require("./log_tool");
const { exec_shell } = require("./shell_tool");
const notifier = require("node-notifier");

/**
 *
 * @param { "error" | "info" | "warning" | ""} type
 * @param {string} message
 * @param {string} title
 * @returns {boolean} 是否点击OK
 */
async function showAlert(type = "info", message, title = "提示") {
    const os_name = process.platform;
    let str = message;
    const cmd = [];
    const cwd = shareData.AUTOMATOR_ROOT;
    if (os_name === "linux") {
        str = str.replace(/[<>]/g, "");
        cmd.push("zenity");
        cmd.push(`--${type}`);
        cmd.push("--text") && cmd.push(str);
        cmd.push("--title") && cmd.push(title);
        if (str.length > 30) cmd.push("--width") && cmd.push("300");
        // return codes in macOS are exactly as in Linux
        // 0 for 'OK', 1 for 'Cancel'
    } else if (os_name === "darwin") {
        switch (
            type // Set dialog icon
        ) {
            case "error":
                type = 0;
                break;
            case "info":
                type = 1;
                break;
            case "warning":
                type = 2;
                break;
            default:
                type = "";
        }

        str = str.replace(/"/g, "'"); // double quotes to single quotes
        cmd.push("osascript") && cmd.push("-e");
        var script = 'tell app "System Events" to display dialog ';
        script += `"${str}" with title "${title}" buttons "OK"`;
        script += ` with icon ${type}`;
        cmd.push(script);
    } else {
        // windows

        // return codes for Windows (default value minus 1)
        // defaults in https://www.tutorialspoint.com/vbscript/vbscript_dialog_boxes.htm

        // 0 - vbOK
        // 1 - vbCancel
        // 2 - vbAbort
        // 3 - vbRetry
        // 4 - vbIgnore
        // 5 - vbYes
        // 6 - vbNo

        switch (
            type // Set MsgBox icon
        ) {
            case "error":
                type = 16;
                break;
            case "info":
                type = 64;
                break;
            case "warning":
                type = 48;
                break;
            default:
                type = 0;
        }

        str = str.replace(/"/g, "'"); // double quotes to single quotes

        // msgbox.vbs script from http://stackoverflow.com/questions/774175
        cmd.push("cscript");

        const vbs_file = `${shareData.AUTOMATOR_ROOT}/scripts/msgbox.vbs`;
        const exist = get_fst_file(vbs_file);
        if (!exist) {
            // 本地不存在脚本需要生成
            write_plain(
                vbs_file,
                `Set objArgs = WScript.Arguments
messageText = objArgs(0)
messageType = objArgs(1)
messageTitle = objArgs(2)
retValue = MsgBox(messageText, messageType, messageTitle)
WScript.Quit (retValue - 1)`,
            );
        }
        cmd.push(vbs_file);
        cmd.push(str) && cmd.push(type) && cmd.push(title);
    }
    const ret = await exec_shell({
        cmd: cmd,
        cwd: cwd,
        capture_stdout: true,
    });
    return ret;
}

async function showNotify(data) {
    const options = Object.assign(
        {
            title: "",
            message: "<空>",
            // actions: ["OK"],
        },
        data,
    );
    const ret = await new Promise((resolve) => {
        notifier.notify(options, (_err, _resp, meta) => {
            resolve(meta.button);
        });
    });
    return ret;
}

module.exports = {
    showAlert,
    showNotify,
};
